package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Role;
import cn.wolfcode.mapper.RoleMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IRoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Override
    @Transactional
    public void delete(Long id) {
        roleMapper.deleteByPrimaryKey(id);
        // 当角色表删除的时候,与他有关的中间表也要删除
        roleMapper.deleteByRelation(id);
    }

    @Override
    @Transactional
    public void insert(Role role, Long[] permissionIds) {
        roleMapper.insert(role);
        // 将所有的权限遍历的添加到角色上
        if (permissionIds != null && permissionIds.length > 0) {
            for (Long permissionId : permissionIds) {
                // 添加关系方法
                roleMapper.insertRelation(role.getId(), permissionId);
            }
        }
    }

    @Override
    @Transactional
    public void update(Role role, Long[] permissionIds) {
        roleMapper.updateByPrimaryKey(role);
        // 当从编辑页面 点击保存按钮时,将之前的关系删除 不然之前的权限会叠加在一起
        roleMapper.deleteByRelation(role.getId());
        // 再分配权限关系
        if (permissionIds != null && permissionIds.length > 0) {
            for (Long permissionId : permissionIds) {
                // 每个角色分配权限
                roleMapper.insertRelation(role.getId(), permissionId);
            }
        }
    }

    @Override
    public Role get(Long id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Role> listAll() {
        return roleMapper.selectAll();
    }

    @Override
    public PageInfo<Role> query(QueryObject qo) {
        // 使用分页插件，传入当前页，每页显示数量
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        // 返回查询一页展示的数据
        return new PageInfo<>(roleMapper.selectForList(qo));
    }


    // 通过员工的id查询角色的id
    @Override
    public List<Role> queryByEmployeeId(Long employeeId) {
        return roleMapper.selectByEmployeeId(employeeId);
    }
}
